# -*- coding: utf-8 -*-
#    CoreDesk - a powerfull jabber client
#    Copyright (C) 2009  Jean-Baptiste Gury <jeanbaptiste.gury@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sqlite3
import CoreDeskTools
import os.path

class DBProxy(object):
    """This class represents a proxy to store data type
    
    """
    
    def _getIdSession(self): return self._idSession

    def _setIdSession(self, idsession) : self._idSession = idsession

    def __getConnection(self):
        if self.__connection == None and self._idSession != None:
            dir = CoreDeskTools.getCoredeskDir()
            pathSession = os.path.join(dir, unicode(self.idsession))
            db = os.path.join(pathSession,  u"cd"+unicode(self.idsession)+u".db")
            self.__connection = sqlite3.connect(db)
            return self.__connection
        elif self._idSession == None:
            return None
        else :
            return self.__connection
        
    connection = property(__getConnection)
    idsession = property(_getIdSession, _setIdSession)

    def __init__(self,idsession):
        self._idSession = idsession
        self.__connection = None

    def createOrUpdateObject(self, obj):
        classname = unicode(type(obj).__name__)
        modulename = unicode(classname.lower())
        if hasattr(eval(modulename), u'DBStore'+classname):
            dbClass = getattr(eval(modulename),u'DBStore'+classname)
            dbInstance = dbClass()
            dbInstance.createOrUpdate(obj)
            

    def deleteObject(self,obj):
        classname = unicode(type(obj).__name__)
        modulename = unicode(classname.lower())
        if hasattr(eval(modulename), u'DBStore'+classname):
            dbClass = getattr(eval(modulename),u'DBStore'+classname)
            dbInstance = dbClass()
            dbInstance.delete(obj)

    def getObject(self):
        classname = unicode(type(obj).__name__)
        modulename = unicode(classname.lower())
        if hasattr(eval(modulename), u'DBStore'+classname):
            dbClass = getattr(eval(modulename),u'DBStore'+classname)
            dbInstance = dbClass()
            dbInstance.get(obj)


# ------
    
    

    
    
        
        
